<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>中国象棋</title>
    <script type="text/javascript" src="jquery-1.8.2.js"></script>
    <style type="text/css">
        .piece{ cursor: pointer; border: 2px black solid; border-radius: 50%; text-align: center; position: absolute; background-color: white; }
        .piece-selected { border: 1px green solid; }
        .piece-null { border: 1px #CCC solid; cursor: pointer; position: absolute; }
    </style>
    <script type="text/javascript">
        String.prototype.format = function () {
            if (arguments.length === 0) {
                return this;
            }
            var params = [];
            if (arguments.length === 1 && arguments[0] instanceof Array) {
                params = arguments[0];
            } else {
                params = arguments;
            }
            for (var s = this, i = 0; i < params.length; i++) {
                if (params[i] === undefined) {
                    continue;
                }
                s = s.replace(new RegExp("\\{" + i + "\\}", "g"), params[i] === undefined ? '' : params[i]);
            }
            return s;
        };

        var context;
        var column = 10, row = 9, interval = 90;
        var x, y, width, height, border, pieceRadius, bitmapWidth, bitmapHeight;

        function initializeConfig() {
            width = interval * (row - 1);
            height = interval * (column - 1); 
            pieceRadius = parseInt(interval / 3);
            border = parseInt(interval / 2);
            x = y = border;
            bitmapWidth = width + border * 2;
            bitmapHeight = height + border * 2;
        }

        function initializeCheckerboard() {
            context.beginPath();
            context.strokeStyle = 'black';
            context.strokeRect(x, y, width, height);
            // column
            var newColumn = column - 2;
            for (var i = 1; i <= newColumn; i++) {
                var currentWidth = i * interval + border;
                context.moveTo(border, currentWidth);
                context.lineTo(width + border, currentWidth);
            }
            // row
            var newRow = row - 2;
            for (var i = 1; i <= newRow; i++) {
                var currentHeight = i * interval + border;
                context.moveTo(currentHeight, border);
                context.lineTo(currentHeight, interval * 4 + border);
                context.moveTo(currentHeight, interval * 5 + border);
                context.lineTo(currentHeight, height + border);
            }

            var chuPalaces = [
                [[4, 1],  [6, 3]], 
                [[4, 3],  [6, 1]],
                [[4, 8],  [6, 10]], 
                [[4, 10], [6, 8]]
            ];
            var palacePosition, palaceTmpX, palaceTmpY;
            for (var i = 0; i < chuPalaces.length; i++) {
                var palacePositions = chuPalaces[i];

                palacePosition = palacePositions[0];
                palaceTmpX = (palacePosition[0] - 1) * interval + border;
                palaceTmpY = (palacePosition[1] - 1) * interval + border;
                context.moveTo(palaceTmpX, palaceTmpY);

                palacePosition = palacePositions[1];
                palaceTmpX = (palacePosition[0] - 1) * interval + border;
                palaceTmpY = (palacePosition[1] - 1) * interval + border;
                context.lineTo(palaceTmpX, palaceTmpY); 
            }

            var createFlag = function (flagPositions) {
                var flagBorder = border / 4;
                var flagLength = interval / 5;
                var flagTmpX, flagTmpY;
                for (var i = 0; i < flagPositions.length; i++) {
                    var currentSoldier = flagPositions[i];
                    var tmpX = (currentSoldier[0] - 1) * interval + border;
                    var tmpY = (currentSoldier[1] - 1) * interval + border;
                    if (i !== 0) {
                        flagTmpX = tmpX - flagBorder;
                        flagTmpY = tmpY + flagBorder;
                        context.moveTo(flagTmpX, flagTmpY);
                        context.lineTo(flagTmpX, flagTmpY + flagBorder);
                        context.moveTo(flagTmpX + 1, flagTmpY);
                        context.lineTo(flagTmpX - flagBorder, flagTmpY);

                        flagTmpX = tmpX - flagBorder;
                        flagTmpY = tmpY - flagBorder;
                        context.moveTo(flagTmpX, flagTmpY);
                        context.lineTo(flagTmpX, flagTmpY - flagBorder);
                        context.moveTo(flagTmpX + 1, flagTmpY);
                        context.lineTo(flagTmpX - flagBorder, flagTmpY);
                    }
                    if (i !== (flagPositions.length - 1 - 2)) {
                        flagTmpX = tmpX + flagBorder;
                        flagTmpY = tmpY + flagBorder;
                        context.moveTo(flagTmpX, flagTmpY);
                        context.lineTo(flagTmpX, flagTmpY + flagBorder);
                        context.moveTo(flagTmpX - 1, flagTmpY);
                        context.lineTo(flagTmpX + flagBorder, flagTmpY);

                        flagTmpX = tmpX + flagBorder;
                        flagTmpY = tmpY - flagBorder;
                        context.moveTo(flagTmpX, flagTmpY);
                        context.lineTo(flagTmpX, flagTmpY - flagBorder);
                        context.moveTo(flagTmpX - 1, flagTmpY);
                        context.lineTo(flagTmpX + flagBorder, flagTmpY);
                    }
                }
            }
            var chuFlagPositions = [
                [1, 4], [3, 4], [5, 4], [7, 4], [9, 4],
                [2, 3], [8, 3]
            ];
            createFlag(chuFlagPositions);
            var hanFlagPositions = [
                [1, 7], [3, 7], [5, 7], [7, 7], [9, 7],
                [2, 8], [8, 8]
            ];
            createFlag(hanFlagPositions);

            var riveHalfWidth = interval * 5.5;
            var riveHalfAvg = parseInt(riveHalfWidth / 4);
            var riverFontSize = interval - interval / 4;
            var riverFontY = 4 * interval + border + riverFontSize;
            var riverStrings = ['楚    河', '漢    界'];
            context.font = riverFontSize + "px Verdana";
            // context.strokeText(riverStrings[0], riveHalfAvg, riverFontY);
            // context.strokeText(riverStrings[1], riveHalfWidth, riverFontY);
            context.fillText(riverStrings[0], riveHalfAvg, riverFontY);
            context.fillText(riverStrings[1], riveHalfWidth, riverFontY);
            context.stroke();
            context.closePath();
        }

        function initializePiece() {
            var chuPieces = [
                ['車', [1, 1]], ['馬', [2, 1]], ['相', [3, 1]], ['士', [4, 1]], 
                ['帅', [5, 1]], ['士', [6, 1]], ['相', [7, 1]], ['馬', [8, 1]], 
                ['車', [9, 1]], ['炮', [2, 3]], ['炮', [8, 3]], ['兵', [1, 4]], 
                ['兵', [3, 4]], ['兵', [5, 4]], ['兵', [7, 4]], ['兵', [9, 4]]
            ];

            var hanPieces = [
                ['車', [1, 10]], ['馬', [2, 10]], ['象', [3, 10]], ['士', [4, 10]], 
                ['将', [5, 10]], ['士', [6, 10]], ['象', [7, 10]], ['馬', [8, 10]], 
                ['車', [9, 10]], ['炮', [2, 8]], ['炮', [8, 8]], ['卒', [1, 7]], 
                ['卒', [3, 7]], ['卒', [5, 7]], ['卒', [7, 7]], ['卒', [9, 7]]
            ];
            
            var styleString;
            for (var i = 0; i < chuPieces.length; i++) {
                var pieceInfo = chuPieces[i];
                var pieceText = pieceInfo[0];
                var piecePosition = pieceInfo[1];
                var pieceLeft = (piecePosition[0] - 1) * interval + border - pieceRadius + 8;
                var pieceTop = (piecePosition[1] - 1) * interval + border - pieceRadius + 8;
                var pieceElem = document.createElement('div');
                pieceElem.className = 'piece';
                styleString = 'border-color: red; color: red;';
                styleString += 'font-size: {0}px;'.format(pieceRadius);
                styleString += 'width:{0}px; height:{0}px; line-height:{0}px;'.format(pieceRadius * 2);
                styleString += 'left: {0}px; top: {1}px;'.format(pieceLeft, pieceTop);
                pieceElem.style = styleString;
                pieceElem.innerText = pieceText;
                pieceElem.setAttribute('data-x', piecePosition[0]);
                pieceElem.setAttribute('data-y', piecePosition[1]);
                document.body.appendChild(pieceElem);
            }
            for (var i = 0; i < hanPieces.length; i++) {
                var pieceInfo = hanPieces[i];
                var pieceText = pieceInfo[0];
                var piecePosition = pieceInfo[1];
                var pieceLeft = (piecePosition[0] - 1) * interval + border - pieceRadius + 8;
                var pieceTop = (piecePosition[1] - 1) * interval + border - pieceRadius + 8;
                var pieceElem = document.createElement('div');
                pieceElem.className = 'piece';
                styleString = 'border-color: black; color: black;';
                styleString += 'font-size: {0}px;'.format(pieceRadius);
                styleString += 'width:{0}px; height:{0}px; line-height:{0}px;'.format(pieceRadius * 2);
                styleString += 'left: {0}px; top: {1}px;'.format(pieceLeft, pieceTop);
                pieceElem.style = styleString;
                pieceElem.innerText = pieceText;
                pieceElem.setAttribute('data-x', piecePosition[0]);
                pieceElem.setAttribute('data-y', piecePosition[1]);
                document.body.appendChild(pieceElem);
            }
        }

        function pieceMove(element, position) {
            var left = (position[0] - 1) * interval + border - pieceRadius + 8;
            var top = (position[1] - 1) * interval + border - pieceRadius + 8;
            element.data('x', position[0]);
            element.data('y', position[1]);
            element.css({'left': '{0}px'.format(left), 'top': '{0}px'.format(top)});
        }

        function clearAll() {
            // context.clearRect(0, 0, bitmapWidth, bitmapHeight);
            $('canvas').remove();
            $('div.piece').remove();
        }

        var getPieces = function () {
            var pieces = [];
            $('div.piece').each(function (index, item) {
                var _this = $(item);
                var currentX = parseInt(_this.data('x'));
                var currentY = parseInt(_this.data('y'));
                pieces.push([_this.text(), [currentX, currentY]]);
            });
            return pieces;
        };

        var refreshCheckerboard = function () {
            $('div.piece-null').remove();
            var pieces = getPieces();
            var styleString;
            for (var c = 1; c <= column; c++) {
                for (var r = 1; r <= row; r++) {
                    var piecePosition = [r, c];
                    var index = -1;
                    for (var i = 0; i < pieces.length; i++) {
                        if (pieces[i][1][0] === piecePosition[0] && 
                            pieces[i][1][1] === piecePosition[1]) {
                            index = i;
                            break;
                        }
                    }
                    if (index <= -1) {
                        var pieceLeft = (piecePosition[0] - 1) * interval + border - pieceRadius + 8;
                        var pieceTop = (piecePosition[1] - 1) * interval + border - pieceRadius + 8;
                        var pieceElem = document.createElement('div');
                        pieceElem.className = 'piece-null';
                        styleString = 'width:{0}px; height:{0}px; line-height:{0}px;'.format(pieceRadius * 2);
                        styleString += 'left: {0}px; top: {1}px;'.format(pieceLeft, pieceTop);
                        pieceElem.style = styleString;
                        pieceElem.setAttribute('data-x', piecePosition[0]);
                        pieceElem.setAttribute('data-y', piecePosition[1]);
                        document.body.appendChild(pieceElem);
                    }
                }
            }
        };

        window.onload = function () {
            initializeConfig();
            var canvasElem = document.createElement('canvas');
            canvasElem.width = bitmapWidth;
            canvasElem.height = bitmapHeight;
            canvasElem.style = 'border:1px black solid;';
            document.body.appendChild(canvasElem);
            if (canvasElem.getContext) {
                context = canvasElem.getContext('2d');
                initializeCheckerboard();
                initializePiece();
                refreshCheckerboard();
            } else {
                throw '浏览器不支持canvas绘图!';
            }
        }

        $(function () {
            $(document).on('mousewheel DOMMouseScroll', function(e) {
                var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) || 
                            (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1));
                if (delta > 0) {
                    interval++;
                } else {
                    interval--;
                }
                clearAll();
                window.onload();
                return false;
            });
            
            var currentSelected;
            $(document).on('click', 'div.piece', function () {
                // 有选择表示吃子, 不然就选中当前棋子
                if (currentSelected) {
                    var _this = $(this);
                    var currentX = parseInt(_this.data('x'));
                    var currentY = parseInt(_this.data('y'));
                    var currentSelectedX = parseInt(currentSelected.data('x'));
                    var currentSelectedY = parseInt(currentSelected.data('y'));
                    if (currentX === currentSelectedX && 
                        currentY === currentSelectedY) {
                        currentSelected = undefined;
                        return false;
                    }
                    _this.remove();
                    pieceMove(currentSelected, [currentX, currentY]);
                    currentSelected = undefined;
                    refreshCheckerboard()
                } else {
                    currentSelected = $(this);
                    currentSelected.addClass('piece-selected')
                }
            });

            $(document).on('click', 'div.piece-null', function () {
                if (!currentSelected) {
                    alert('请选择棋子!');
                    return false;
                }
                var _this = $(this);
                var pieceText = _this.text();
                var currentX = parseInt(_this.data('x'));
                var currentY = parseInt(_this.data('y'));
                if (pieceText === '炮') {
                    
                }


                pieceMove(currentSelected, [currentX, currentY]);
                currentSelected = undefined;
                refreshCheckerboard();
            });

        });

    </script>
</head>
<body>
    
</body>
</html>